package hottargui.config;

import hottargui.framework.*;
import hottargui.standard.*;

public class BetaAttackState implements TarguiState {

	Game gameContext;
	Position basePos;
	Position targetPos;
	
	public BetaAttackState(Game game, Position base, Position target)
	{
		gameContext = game;
		basePos = base;
		targetPos = target;
	}
	
	public boolean buy(int count, Position deploy) throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public State getState() {
		return State.attack;
	}

	public PlayerColor getWinner() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public boolean move(Position from, Position to, int count) throws IllegalActionException {
		if ( from.equals(basePos) && to.equals(targetPos) && count > 0 )
		{
			Tile target = gameContext.getTile(targetPos);
			Tile base = gameContext.getTile(basePos);
			
			if ( target.getUnitCount() == 0 )
			{
				if ( base.getUnitCount() >= count )
				{
					target.setOwnerColor(base.getOwnerColor());
					
					base.setUnitCount(base.getUnitCount() - count);
					target.setUnitCount(count);
					
					gameContext.setState(gameContext.getFactory().getBuyState(gameContext));
					return true;
				}
			}
		}
		
		return false;
	}

	public void newGame() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}

	public void rollDie() throws IllegalActionException {
		Tile baseTile = gameContext.getTile(basePos);
		Tile targetTile = gameContext.getTile(targetPos);
		
		AttackStrategy as = gameContext.getGameObjectServer().getAttackStrategy();
		DiceRollStrategy drs = gameContext.getGameObjectServer().getDiceRollStrategy();
		
		int die = drs.rollDie();
		gameContext.getGameObjectServer().getGameData().setLastDieRoll(die);
		
		int killed = as.attack(baseTile, targetTile, die);
		((StandardGame)gameContext).report("Attack killed "+killed+" enemy units");
		
		targetTile.setUnitCount(targetTile.getUnitCount() - killed);
		
		if ( targetTile.getUnitCount() > 0 )
		{
			gameContext.setState(gameContext.getFactory().getDefendState(gameContext, basePos, targetPos));
		}
		else
		{
			((StandardGame)gameContext).report("Enemy was eliminated!");
			// target eliminated
			targetTile.setOwnerColor(PlayerColor.None);
		}
	}

	public PlayerColor turnCard() throws IllegalActionException {
		throw new IllegalActionException(this.getState());
	}
	
	public void yieldAttack() throws IllegalActionException
	{
		// abort attack
		gameContext.setState(gameContext.getFactory().getBuyState(gameContext));
	}
	
	public void skip() throws IllegalActionException
	{
		throw new IllegalActionException(this.getState());
	}
}
